<?php
// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\user\model\Address as AddressModel;
use app\common\model\Area;
use service\ApiReturn;
use think\Db;

/**
 * 用户收货地址
 * Class UserAddress
 * @package app\api\controller\v1
 */
class UserAddress extends Base
{

    /**
     * 地址列表
     * @param array $data
     * @param array $user
     * @author 似水星辰 [ 2630481389@qq.com ]
     * @since 2019/4/11 13:40
     * @return \think\response\Json
     */
    public function address_list($data = [], $user = [])
    {
        $where[] = ['user_id', 'eq', $user['id']];
        $addressList = AddressModel::where($where)->field("address_id,name,is_default,mobile,address,province,city,district,postal_code,sex,label_name")->order("address_id desc")->select();
        return ApiReturn::r(1, $addressList, '请求成功');
    }

    /**
     * 添加收货地址
     * @param array $data
     * @param array $user
     * @author 似水星辰 [ 2630481389@qq.com ]
     * @created 2019/9/23 17:40
     */
    public function add_address($data = [], $user = [])
    {
       
        $count = AddressModel::where("user_id",$user['id'])->count();    
        //第一个地址必须是默认
        if($count < 1){
            $data['is_default']  = 1;
        }else if ($data['is_default'] == 1) {
            //去除用户默认地址
            $where[] = ['user_id', 'eq', $user['id']];
            $where[] = ['is_default', 'eq', 1];         
            AddressModel::where($where)->update(['is_default' => 0]);         
        }
        //进行添加
        $data['user_id'] = $user['id'];
        $data['status'] = 1;
        $province_id = Area::getIdByName($data['province'], 1);
        $data['province_id'] = $province_id ?: 0;
        $city_id = Area::getIdByName($data['city'], 2, $data['province_id']);
        $data['city_id'] = $city_id ?:0;
        $district_id = Area::getIdByName($data['district'], 3, $data['city_id'],$data['district']);
        $data['district_id'] = $district_id ?: 0;
        $data['create_time'] = time();
        
        $res = $this->validate($data, \app\user\validate\Address::class);
        if(true !== $res){       
            return ApiReturn::r(0, [], $res);
        }        
        $result = AddressModel::create($data);
        if ($result) {
            $data['address_id'] = $result->address_id;
            return ApiReturn::r(1, $data, '添加成功');
        }
        return ApiReturn::r(0, [], '添加失败');
    }

    /**
     * 获得单条收货地址
     * @param array $data
     * @param array $user
     * @author  风轻云淡
     * @return \think\response\Json
     */
    public function get_one_address($data = [], $user = [])
    {
        if($data['address_id']){
            $addressId = $data['address_id'];
            $where[] = ['address_id', 'eq', $addressId];
        }else{
            $where[] = ['is_default', 'eq', 1];
        }
        $where[] = ['user_id', 'eq', $user['id']];
        $getAddress = AddressModel::get_one_address($where);
        if ($getAddress) {
            return ApiReturn::r(1, $this->filter($getAddress), '请求成功');
        } 
        return ApiReturn::r(0, [], '暂无数据');
    }

    /**
     * 修改收货地址
     * @param array $data
     * @param array $user
     * @author 似水星辰 [ 2630481389@qq.com ]
     * @created 2019/9/23 17:39
     */
    public function edit_address($data = [], $user = [])
    {
        Db::startTrans();
        try{
            if ($data['is_default'] == 1) {
                //取消所有的默认地址
                AddressModel::where(['user_id'=>$user['id'],'is_default'=>1])->update(['is_default' => 0]);
            }
            if (isset($data['province']) && $data['province'] != '') {
                $data['province_id'] = Area::getIdByName($data['province'], 1);
                if (isset($data['city']) && $data['city'] != '') {
                    $data['city_id'] = Area::getIdByName($data['city'], 2, $data['province_id']);
                    if (isset($data['district']) && $data['district'] != '') {
                        $data['district_id'] = Area::getIdByName($data['district'], 3, $data['city_id']);
                    }
                }
            }
            $data["label_name"] = $data["label_name"] ??  "";
            $data["user_id"] = $user['id'];            
            $res = $this->validate($data, \app\user\validate\Address::class);
            if(true !== $res){
                exception($res);
            }  
            
            $result = AddressModel::where(['address_id' => $data['address_id'],'user_id'=>$user['id']])->update($data);
            if(!$result){
                exception('修改失败');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }
        return ApiReturn::r(1, [], '修改成功');
    }

    /**
     * 删除收货地址
     * @param array $data
     * @param array $user
     * @author  风轻云淡
     * @return \think\response\Json
     */
    public function del_address($data = [], $user = [])
    {
        $addressIds = $data['address_ids'];
        $where[] = ['address_id', 'in', explode(",", rtrim($addressIds, ","))];
        $where[] = ['user_id', 'eq', $user['id']];
        $result = AddressModel::where($where)->delete();
        if ($result) {
            return ApiReturn::r(1, [], '删除成功');
        }
        return ApiReturn::r(0, [], '删除失败！');
    }

    /**
     * 修改为默认收货地址
     * @param array $data
     * @param array $user
     * @author 似水星辰 [ 2630481389@qq.com ]
     * @created 2019/9/23 17:39
     */
    public function is_default($data = [], $user = [])
    {
        Db::startTrans();
        try{
            //取消所有的默认地址
            $userAddress = AddressModel::where(['user_id'=>$user['id'],'is_default'=>1])->update(['is_default' => 0]);
            //修改默认收货地址
            $result = AddressModel::where(['user_id' => $user['id'], 'address_id' => $data['address_id']])->update(['is_default' => 1]);
            if(!$result){
                exception('设置默认地址失败');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }
        return ApiReturn::r(1, [], '操作成功');
    }
    
    /**
     * 获取全国城市信息
     * @param array $data
     * @param array $user
     * @author 似水星辰 [ 2630481389@qq.com ]
     * @created 2019/9/23 17:39
     */
    public function getCity($data = []){
       $where=['pid'=>($data['pid']?$data['pid']:0)];
       $area = Db::name('china_area')->where($where)->select();
       return ApiReturn::r(1, ['list'=>$area], '操作成功');
    }
    
     /*
     * 保存用户地址标签
     *
     */
    public function save_label($data = [], $user = [])
    {
        $insert = [
            'name' => $data['name'],
            'user_id' => $user['id'],
            'create_time' => time(),
            'is_public' => 0
        ];
        Db::name("user_address_label")->insert($insert);
        return ApiReturn::r(1, [], 'ok');
    }

    /*
     * 编辑用户地址标签
     *
     */
    public function edit_label($data = [], $user = [])
    {
        Db::name("user_address_label")->where([
            'user_id' => $user['id'],
            'id' => $data['id']
        ])->update(['name' => $data['name']]);
        return ApiReturn::r(1, [], 'ok');
    }

    /*
     * 获取用户地址标签
     *
     */
    public function get_label($data = [], $user = [])
    {
        $res = Db::name("user_address_label")->where([
            'user_id' => $user['id']
        ])
            ->whereOr([
                'is_public' => 1
            ])->select();
        return ApiReturn::r(1, $res, 'ok');
    }
    
     /**
     * Notes: 获取国际手机区号
     * User: chenchen
     * Date: 2021/5/22
     * Time: 14:56
     * @param array $data
     * @param array $user
     */
    public function area_code($data = [], $user = [])
    {
        $list = Db::name("phone_prefix")->select();
        $res = [];
        foreach ($list as $v) {
            $res[$v['letter']][] = [
                'country' => $v["country"] . ' +' . $v["prefix"],
                'prefix' => $v["prefix"]
            ];
        }
        if (!empty($res)) {
            ksort($res);
        }
        return ApiReturn::r(1, $res, 'ok');
    }
}